package com.gimi.cloud.jimi.queue.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.exception.MsgException;
import com.gimi.cloud.jimi.common.utils.DateUtil;
import com.gimi.cloud.jimi.common.utils.StringUtil;
import com.gimi.cloud.jimi.commonService.InterfacePlatform.InterfacePlatformRequestService;
import com.gimi.cloud.jimi.dao.dao.User.UserDao;
import com.gimi.cloud.jimi.dao.dao.moreInfo.MoreInfoDao;
import com.gimi.cloud.jimi.dao.dao.sys.SysConfigDao;
import com.gimi.cloud.jimi.dao.redis.IRedisService;
import com.gimi.cloud.jimi.dto.app.moreInfo.DebitcardLoginDTO;
import com.gimi.cloud.jimi.entity.app.moreInfo.MoreInfoEntity;
import com.gimi.cloud.jimi.entity.user.User;
import com.gimi.cloud.jimi.queue.service.FengchaoDebitCardService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @auther loongs
 * @date 2018/1/15  16:00
 */
@Service
public class FengchaoDebitCardServiceImpl implements FengchaoDebitCardService {

    private static final Logger log = LoggerFactory.getLogger(FengchaoDebitCardServiceImpl.class);
    private IRedisService iRedisService;
    private InterfacePlatformRequestService ipRequestService;
    private MoreInfoDao moreInfoDao;
    private UserDao userDao;
    private SysConfigDao sysConfigDao;
    //最大容错次数暂时定为3次
    private final Integer MAXTIMES = 3;

    private final static String INTERFACE_PLATFORM_UNIVERSAL_DEBITCARD="interface_platform_universal_debitCard";

    @Autowired
    public FengchaoDebitCardServiceImpl(IRedisService iRedisService, InterfacePlatformRequestService ipRequestService,
                                        MoreInfoDao moreInfoDao, UserDao userDao, SysConfigDao sysConfigDao) {
        this.iRedisService = iRedisService;
        this.ipRequestService = ipRequestService;
        this.moreInfoDao = moreInfoDao;
        this.userDao = userDao;
        this.sysConfigDao = sysConfigDao;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED)
    public void getReport(Message message, Channel channel, DebitcardLoginDTO debitcardLoginDTO) throws Exception {
        log.info("开始工资卡抓取数据接口");

        log.info("验证参数");
        if (debitcardLoginDTO == null || StringUtil.isBlank(debitcardLoginDTO.getUserId()) || StringUtil.isBlank(debitcardLoginDTO.getSurnameSid())) {
            throw new MsgException(ResponseCodeEnum.DEBIT_IS_NOT_FOUND);
        }
        User user = userDao.getUserByUserId(debitcardLoginDTO.getUserId());
        if (user == null) {
            throw new MsgException(ResponseCodeEnum.ERR_USER_INVALID);
        }
        //查询该用户之前是否有获取过信用卡邮箱账单，需要获取状态为获取中
        MoreInfoEntity moreInfoEntity = moreInfoDao.getMoreInfoByUserIdAndTypeAndData(debitcardLoginDTO.getUserId(),3,1);
        if (moreInfoEntity == null || moreInfoEntity.getGetdataErrorTimes() >= MAXTIMES ) {
            throw new MsgException(ResponseCodeEnum.DEBIT_DATA_ERROR_TIMES_IS_OUT_OF_TIMES);
        }

        boolean flagIsSuccess=false;

        log.info("读取数据库配置配置表");
        String fengchao_creditCardEmail = sysConfigDao.getConfigByKey(INTERFACE_PLATFORM_UNIVERSAL_DEBITCARD);
        JSONObject feJson = JSON.parseObject(fengchao_creditCardEmail);
        JSONObject obtainbills = feJson.getJSONObject("get_debit_card_credits_report");

        JSONObject body = obtainbills.getJSONObject("body");

        //可不传
        //body.put("dataLimit",  "");
        body.put("surnameSid",debitcardLoginDTO.getSurnameSid());
        obtainbills.put("body", body);
        log.info("拼接请求参数："+obtainbills);
        log.info("发起请求获取工资卡抓取数据开始");
        String sendApiPost = ipRequestService.sendApiPost(obtainbills.toJSONString());
        log.info("返回结果为："+sendApiPost);

        JSONObject reportJson = JSON.parseObject(sendApiPost);
        JSONObject reportbody = reportJson.getJSONObject("body");
        JSONObject data=reportbody.getJSONObject("data");
        String type = reportbody.getString("type");
        //1代表成功返回url，2代表上传失败返回原始数据
        if(reportbody!= null && "1".equals(type)){
            flagIsSuccess=true;
        }
        //存入数据
            if(flagIsSuccess){
                moreInfoEntity.setReportData(data.getString("ossUrl"));
                moreInfoEntity.setGetdataErrorTimes(0);
                moreInfoEntity.setGetdata("2");
                moreInfoEntity.setGetdataTime(DateUtil.getNow());

                //TODO 有效时长，等风控规则
                moreInfoEntity.setReportEffectionBegin(DateUtil.getNow());
                moreInfoEntity.setReportEffectionEnd(DateUtil.getLateYear(1));
            }else {
                moreInfoEntity.setGetdataErrorTimes(moreInfoEntity.getGetdataErrorTimes()==null?0:moreInfoEntity.getGetdataErrorTimes()+1);
                moreInfoEntity.setGetdata("3");
            }
             moreInfoEntity.setUpdateUid(user.getUserId());
             moreInfoEntity.setUpdateUname(user.getAddUname());
             moreInfoEntity.setUpdateTime(DateUtil.getNow());
            moreInfoDao.updateByPrimaryKey(moreInfoEntity);

        log.info("发起请求获取工资卡结束");
    }
}
